package com.sto.stoapp.activity.scanner;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.BaseRequest;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.DateUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.TraceUtil;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHomeActivity;

import java.util.ArrayList;
import java.util.List;

public class StoYouPaiWuQianQueryActivity extends StoHomeActivity {

	StoHhmEditText dateEditText;
	Button selectDateButton, queryButton;
	ItemAdapter adapter;
	ListView listView;
	List<String> allCodes = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.youpaiwuqian_layout);
		String action = getIntent().getStringExtra("busiType");
		this.setTitleBottom("有派无签查询", action);
		dateEditText = (StoHhmEditText) findViewById(R.id.date);
		selectDateButton = (Button) findViewById(R.id.select_date);
		queryButton = (Button) findViewById(R.id.query_button);
		dateEditText.setText(DateUtil.getTodayDate("-"));
		listView = (ListView) findViewById(R.id.list_view);
		adapter = new ItemAdapter(this, allCodes);
		listView.setAdapter(adapter);
		selectDateButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dateSetDialog();
			}
		});
		queryButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(StoYouPaiWuQianQueryActivity.this,"查询无结果",Toast.LENGTH_SHORT).show();
				//doQuery(dateEditText.getText().toString());
			}
		});
	}

	// 获取日期的Dialog
	private void dateSetDialog() {
		final DatePicker datePicker = new DatePicker(this);
		int year = datePicker.getYear();
		int month = datePicker.getMonth();
		int dayOfMonth = datePicker.getDayOfMonth();

		OnDateSetListener callBack = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {

				int month = monthOfYear + 1;
				String strMonth = null;
				String strDayOfMonth = null;
				if (0 < month && month < 10) {
					strMonth = "0" + month;
				} else {
					strMonth = "" + month;
				}
				if (0 < dayOfMonth && dayOfMonth < 10) {
					strDayOfMonth = "0" + dayOfMonth;
				} else {
					strDayOfMonth = "" + dayOfMonth;
				}
				String date = new StringBuilder().append(year).append("-")
						.append(strMonth).append("-").append(strDayOfMonth)
						.toString();
				dateEditText.setText("");
				dateEditText.setText(date);

			}
		};
		DatePickerDialog datePickerDialog = new DatePickerDialog(this,
				callBack, year, month, dayOfMonth);

		datePickerDialog.show();
	}

	public void doQuery(String date) {
		allCodes.clear();
		new QueryThread(this, date).start();
	}

	class QueryThread extends BaseThread {
		private String date;
		private Context c;

		public QueryThread(Context context, String date) {
			super(context);
			this.date = date;
			this.c = context;
			showDialog();
		}

		@Override
		public void run() {
			super.run();
			HttpManager mgr = new HttpManager();
			YouPaiWuQianRequest request = new YouPaiWuQianRequest(c, date);
			String result = mgr.doPostClient(request.buildToRequestString(),
					StoFilePreference.getInstance(c).getServerIp()
							+ URLActions.DELIVERY_AND_SIGNATURE_ACTION);

			Gson gs = new Gson();
			try {
				YouPaiWuQianResponse response = gs.fromJson(result,
						new TypeToken<YouPaiWuQianResponse>() {
						}.getType());
				if (allCodes == null) {
					allCodes = new ArrayList<String>();
				}
				if (response.waybillNo != null)
					allCodes.addAll(response.waybillNo);

				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						if (allCodes.size() == 0) {
							Helper.showToast(context, "没有数据");
						} else {
							Helper.showToast(context, "查询成功");
						}
						adapter.notifyDataSetChanged();
					}
				});

			} catch (JsonSyntaxException e) {
				e.printStackTrace();
				ExceptionLog.writeLog(
						"StoYouPaiWuQianQueryActivity.QueryThread", "解析异常："
								+ result);
				showMsg("数据解析异常,查询失败");
			} finally {
				cancelDialog();
			}

		}

		private void showMsg(final String text) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Helper.showToast(context, text);
				}
			});
		}
	}

	class ItemAdapter extends BaseAdapter {

		Context context;
		List<String> codes;

		public ItemAdapter(Context context, List<String> codes) {
			this.context = context;
			this.codes = codes;
		}

		@Override
		public int getCount() {
			return codes.size();
		}

		@Override
		public Object getItem(int position) {
			return codes.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Hold hold;
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.youpaiwuqian_item, null);
				hold = new Hold();
				hold.numberText = (TextView) convertView
						.findViewById(R.id.number);
				hold.codeText = (TextView) convertView.findViewById(R.id.code);
				convertView.setTag(hold);
			} else {
				hold = (Hold) convertView.getTag();
			}
			hold.numberText.setText((getCount() - position) + "");
			hold.codeText.setText(codes.get(getCount() - position - 1));
			return convertView;
		}
	}

	class Hold {
		TextView numberText;
		TextView codeText;
	}

	class YouPaiWuQianRequest extends BaseRequest {

		public YouPaiWuQianRequest(Context c, String queryDate) {
			opOrgCode = StoFilePreference.getInstance(c).getSiteCode();
			deviceType = "PDA";
			opTerminal = StoFilePreference.getInstance(c).getMachineCode();
			tid = StoFilePreference.getInstance(c).getMachineCode();
			opUserCode = StoFilePreference.getInstance(c).getSiteCode()
					+ StoFilePreference.getInstance(c).getUserCode();
			opTime = DateUtil.getDateTime();
			trace = TraceUtil.getTraceTimes();
			sessionId = StoFilePreference.getInstance(c).getSessionId();
			mty = "0820";
			this.queryDate = queryDate;
		}

		public String queryDate;
		public String opOrgCode;
		public String deviceType;
		public String opTerminal;
		public String opUserCode;
		public String opTime;
	}

	class YouPaiWuQianResponse {
		public String sessionId;
		public String tid;

		public String trace;
		public String opOrgCode;
		public String mty;
		public String respMessage;
		public String respCode;
		public List<String> waybillNo;

	}
}
